#include "../include/serverpasswd.h"
#include "../include/cmd.h"

void getSalt(char* salt, char* ciphertext){
    int i,j;
    for(i=0,j=0; ciphertext[i]&&j!=3; ++i){
        if(ciphertext[i] == '$') ++j;
    }
    strncpy(salt, ciphertext, i-1);
}


char* userLogin(int peerfd, char* username){
    char user_name[32] = {0};
    int length = 0;
    char salt[32] = {0};
    char ciphertext[128] = {0};
    int ret = 0;
    while(1){
        //接收用户名
        length = 0;
        memset(user_name, 0, sizeof(user_name));
        ret = recv(peerfd, &length, 4, MSG_WAITALL);
        PASSWORD_CHECK(ret);
        ret = recv(peerfd, user_name, length, MSG_WAITALL);
        PASSWORD_CHECK(ret);
        //根据用户名查询sp
        struct spwd* sp = getspnam(user_name);
        if(sp ==NULL){
            //查询失败，返回给客户端错误
            train_t train;
            memset(&train, 0, sizeof(train));
            strcpy(train.buff, "jijijijibeibeibei");
            train.length = strlen(train.buff);
            ret = send(peerfd, &train, 4+train.length, MSG_WAITALL);
            PASSWORD_CHECK(ret);
            continue;
        }
        else{
            //查询成功，返回给客户端盐值
            getSalt(salt, sp->sp_pwdp);
            train_t train;
            memset(&train, 0, sizeof(train));
            strcpy(train.buff, salt);
            train.length = strlen(train.buff);
            ret = send(peerfd, &train, 4+train.length, MSG_WAITALL);
            PASSWORD_CHECK(ret);
            //等待客户端返回密文
            
            ret = recv(peerfd, &length, 4, MSG_WAITALL);
            PASSWORD_CHECK(ret);
            ret = recv(peerfd, ciphertext, length, MSG_WAITALL);
            PASSWORD_CHECK(ret);

            //密文验证成功
            if(strcmp(sp->sp_pwdp, ciphertext)==0){
                memset(&train, 0, sizeof(train));
                strcpy(train.buff, "yes,you are right!");
                train.length = strlen(train.buff);
                ret = send(peerfd, &train, 4+train.length, MSG_WAITALL);
                PASSWORD_CHECK(ret);
                printf("user:%s log in\n", user_name);
                break;
            }
            //密文验证失败
            else{
                memset(&train, 0, sizeof(train));
                strcpy(train.buff, "bullshit, fuck you!");
                train.length = strlen(train.buff);
                ret = send(peerfd, &train, 4+train.length, MSG_WAITALL);
                PASSWORD_CHECK(ret);
            }
        }
    }
    strcpy(username, user_name);
    return username;
}
